package com.xiaoyun.controller;

import com.xiaoyun.bo.ShopcartBO;
import com.xiaoyun.bo.UserBO;
import com.xiaoyun.constant.Const;
import com.xiaoyun.pojo.Users;
import com.xiaoyun.service.UserService;
import com.xiaoyun.utils.*;
import com.xiaoyun.vo.UsersVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

@Api("用于注册登录的相关接口")
@RequestMapping("passport")
@RestController
@RequiredArgsConstructor
public class PassportController extends BaseController {

    private final UserService userService;


    private final RedisUtil redisUtil;

    @ApiOperation("用户名是否存在")
    @GetMapping("/usernameIsExist")
    public XYJSONResult usernameIsExist(@RequestParam String username) {
        if (StringUtils.isBlank(username)) {
            return XYJSONResult.errorMsg("用户名不能为空");
        }
        boolean isExist = userService.queryUsernameIsExist(username);
        if (isExist) {
            return XYJSONResult.errorMsg("用户名已经存在");
        }
        return XYJSONResult.ok();
    }

    @ApiOperation("用户名注册")
    @PostMapping("/regist")
    public XYJSONResult usernameIsExist(@Valid @RequestBody UserBO userBO,
                                        HttpServletRequest request,
                                        HttpServletResponse response) {
        boolean isExist = userService.queryUsernameIsExist(userBO.getUsername());

        if (isExist) {
            return XYJSONResult.errorMsg("用户名已经存在");
        }
        Users userResult = userService.createUser(userBO);

        UsersVO usersVO = conventUsersVO(userResult);

        CookieUtils.setCookie(request, response, "user",
                JsonUtils.objectToJson(usersVO), true);

        return XYJSONResult.ok();
    }

    @ApiOperation("用户名登录")
    @PostMapping("/login")
    public XYJSONResult login(@Valid @RequestBody UserBO userBO,
                              HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        String username = userBO.getUsername();
        String password = userBO.getPassword();
        Optional<Users> userOptional = userService.queryUserForLogin(username, MD5Utils.getMD5Str(password));
        if (!userOptional.isPresent()) {
            return XYJSONResult.errorMsg("用户名或者密码错误");
        }
        Users userResult = userOptional.get();

        UsersVO usersVO = conventUsersVO(userResult);

        CookieUtils.setCookie(request, response, "user",
                JsonUtils.objectToJson(usersVO), true);

        //同步购物车数据
        synchShopcartData(userResult.getId(), request, response);

        return XYJSONResult.ok(userResult);
    }



    private void synchShopcartData(String userId, HttpServletRequest request,
                                   HttpServletResponse response) {
        String shoppartJsonRedis = redisUtil.getKey(Const.FOODIE_SHOPCART + ":" + userId);
        String shopcartStrCookie = CookieUtils.getCookieValue(request, Const.FOODIE_SHOPCART);
        if (StringUtils.isBlank(shoppartJsonRedis)) {
            redisUtil.setKey(Const.FOODIE_SHOPCART + ":" + userId, shopcartStrCookie);
        } else {
            if (StringUtils.isBlank(shopcartStrCookie)) {
                CookieUtils.setCookie(request, response, Const.FOODIE_SHOPCART, shoppartJsonRedis, true);
            } else {
                List<ShopcartBO> shopcartBOList = mergeList(shoppartJsonRedis, shopcartStrCookie);
                CookieUtils.setCookie(request, response, Const.FOODIE_SHOPCART, JsonUtils.objectToJson(shopcartBOList), true);
                redisUtil.setKey(Const.FOODIE_SHOPCART + ":" + userId, JsonUtils.objectToJson(shopcartBOList));
            }
        }
    }

    private List<ShopcartBO> mergeList(String shoppartJsonRedis, String shopcartStrCookie) {
        Set<ShopcartBO> set = new LinkedHashSet<>();
        List<ShopcartBO> shopcartListRedis = JsonUtils.jsonToList(shoppartJsonRedis, ShopcartBO.class);
        List<ShopcartBO> shopcartListCookie = JsonUtils.jsonToList(shopcartStrCookie, ShopcartBO.class);
        for (ShopcartBO sbRedis : shopcartListRedis) {
            for (ShopcartBO sbCookie : shopcartListCookie) {
                if (sbRedis.getItemId().equals(sbCookie.getItemId()) && sbRedis.getSpecId().equals(sbCookie.getSpecId())) {
                    sbRedis.setBuyCounts(sbCookie.getBuyCounts());
                    set.add(sbRedis);
                    break;
                }
                set.add(sbRedis);
                set.add(sbCookie);
            }
        }
        return set.stream().collect(Collectors.toList());
    }

    @ApiOperation("用户名退出登录")
    @PostMapping("/logout")
    public XYJSONResult logout(@RequestBody String userId,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        CookieUtils.deleteCookie(request, response, "user");
        redisUtil.removeKey(Const.REDIS_USER_TOKEN + ":" + userId);
        CookieUtils.deleteCookie(request, response, Const.FOODIE_SHOPCART);
        return XYJSONResult.ok();
    }

}
